<?php

namespace app\controller\pdf;
use extend\PHPMailer\Exception;
use ZipArchive;

class ZipHelper
{
    protected function randName(): string
    {
        $str = "";
        for($i = 0 ;$i <=10; $i++) {
            $str .= rand(0 , 9);
        }
        return __DIR__ . '/' . md5(microtime(true) . $str) . '.zip';

    }
    public function zipFile(string $pdfName, string $content, $zipFileName, string $password)
    {
        $tmpName = $this->randName();
        $zip = new ZipArchive();
        $res = $zip->open($tmpName, ZipArchive::CREATE | ZipArchive::OVERWRITE);
        if ($res === true) {
            $zip->setPassword($password);
            $zip->addFromString($pdfName, $content);
            if (!$zip->setEncryptionName($pdfName, ZipArchive::EM_AES_256)) {
                throw new Exception('Set encryption failed');
            }
            $zip->close();
        } else {
            throw new Exception("发生异常");
        }
        $content = file_get_contents($tmpName);
        unlink($tmpName);
        Header( "Content-type:application/octet-stream");
        Header( "Accept-Ranges:bytes");
        Header( "Accept-Length:");
        header( "Content-Disposition:  attachment;  filename= $zipFileName");
        echo $content;die();
    }
}